import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  Animated,
  TextInput,
  TouchableOpacity
} from 'react-native';
import styles from './indexStyle';
import api from '../../services/api';
import ToastTip from '../global/ToastTip';
import ImagePicker from 'react-native-image-picker';
import LoadingTip from '../global/LoadingTip';
import JPushModule from 'jpush-react-native';
import EasemobChat from '../global/EasemobChat';

class RegSecondStep extends Component {
    constructor(props) {
		super(props);

		this.state = {
            head: "",
            loadingShow: false,
		};

        this.reg_id = "";

		// this._getTabHeight = this._getTabHeight.bind(this);
		// this._onChangeTab = this._onChangeTab.bind(this);

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentWillMount() {
		// this._retrieveDetails();
        JPushModule.getRegistrationID((reg_id)=>{
            this.reg_id = reg_id;
        });
	}

    async _submitAction(){
        let {head} = this.state;
        let {actions,dispatch,phone,passwd,hk_name,code} = this.props;
        if(!head){
            this.refs.toast.show("请上传相片");
            return;
        }

        this.setState({loadingShow: true});
        // let randNum = this.randomChar();
        let res = await api.post("/housekeeper/reg",{phone,passwd,hk_name,code,keeper_head:head,jpush_tag:this.reg_id});

        // console.log("###", res);
        if(res.cd == 1){
            this.setState({loadingShow: false});
            this.refs.toast.show(res.msg);
        }else{
            
            let r = await api.post("/config/easemob",{ticket:res.data.ticket});
            if (r.cd == 0 && r.data && r.data.group) {
                res.data.group = r.data.group;
            }else{
                res.data.group = "";
            }


            if(res.data.role == 2){//业主管家
                dispatch(actions.session.session_change({...res.data, reload:true}));
                return;
            }

            if(res.data.role == 0 && (!res.data.easemob_kefu_name||!res.data.easemob_kefu_pwd)){//物业管家(没有开通环信)
                dispatch(actions.session.session_change({...res.data, reload:true}));
                return;
            }

            //登录聊天系统
            if(res.data.role == 1 && (!res.data.easemob_kefu_name||!res.data.easemob_kefu_pwd)){
                this.setState({loadingShow: false});
                this.refs.toast.show("未开通消息账户，无法登录!");
                return;
            }

            EasemobChat.chatLogin({uName:res.data.easemob_kefu_name,uPwd:res.data.easemob_kefu_pwd}, (resStr)=>{
                //loading消失
                this.setState({loadingShow: false});
                if(resStr == 'success'){
                    dispatch(actions.session.session_change({...res.data,reload:true}));
                }else{
                    this.refs.toast.show("登录消息失败");
                }
            });
        }
    }

    _cameraAction(){
        var options = {
            title: '请选择',
            cancelButtonTitle: "取消",
            takePhotoButtonTitle: "照相",
            chooseFromLibraryButtonTitle:"选择相册",
            quality: 0.8,
            maxHeight: 138,
            maxWidth: 138,
            storageOptions: {
                skipBackup: true,
                path: 'images'
            }
        };
        // 照片
        ImagePicker.showImagePicker(options, (response)  => {
            // Same code as in above section!
            if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }else{
                if (response.didCancel) {
                   console.log('User cancelled image picker');
                   return;
                }

                this.setState({head:'data:image/jpeg;base64,'+response.data});
            }
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <ScrollView
                    style={styles.scrollContainer}
                    scrollEventThrottle={16}>

                    <View style={[styles.toolsContainer,{paddingLeft:15,paddingRight:15,paddingTop:20,paddingBottom:25}]}>
                        <View style={styles.regSTopHead}>
                            <Image source={require('../../../img/hk_reg_head_icon.png')}/>
                            <Text style={{fontSize:15,color:"#555",textAlign:'center',marginTop:10}}>请上传戴工牌的照片</Text>
                        </View>
                        <View style={styles.regSBottomHead}>
                            <View style={{marginRight:15}}>
                                <Image source={require('../../../img/hk_reg_headleft_icon.png')}/>
                                <Text style={styles.subHeadTitle}>示例图</Text>
                            </View>
                            <TouchableOpacity onPress={this._cameraAction.bind(this)} style={{marginRight:15}}>
                                {this.state.head?
                                    <Image source={{uri:this.state.head}} style={{width:137.5, height:137.5}}/>:
                                    <Image source={require('../../../img/hk_reg_headright_icon.png')} style={{width:137.5, height:137.5}}/>}
                                <Text style={styles.subHeadTitle}>你的照片</Text>
                            </TouchableOpacity>
                        </View>
                    </View>

                    <TouchableOpacity onPress={this._submitAction.bind(this)} style={styles.submitActionPhoneBtn}>
                        <Text style={styles.submitActionText}>提交</Text>
                    </TouchableOpacity>
                </ScrollView>
                <ToastTip ref="toast"/>
                <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
RegSecondStep = connectHelper(state => state)(RegSecondStep);

module.exports = RegSecondStep;
